﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Intorise.Net;
using Intorise.Common;
using System.Net;
using System.Net.Sockets;

namespace NetTest
{
    public partial class Form1 : Form
    {
        string loginUrl = "http://my.37.com/api/login.php?action=login&login_account={0}&password={1}&ajax=1&remember_me=1&save_state=0&ltype=1";
        string enterGameUrl = "http://gameapp.37.com/controller/enter_game.php?game_id=237&sid=3613&showlogintype=1";
        string registerServerUrl = "";

        NetTools net = new NetTools();
        CookieContainer cookies = new CookieContainer();

        public Form1()
        {
            InitializeComponent();
            ConsoleBLL.TextBox = this.richTextBox1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConsoleBLL.WriteLine("开始登录...");
            var request = net.SendRequest(string.Format(loginUrl, "intorise", "zpf800823"), "GET", cookies);
            //request.Headers.Add("X-Requested-With:XMLHttpRequest");
            //request.Accept = "application/json, text/javascript, */*; q=0.01";
            //request.Referer = "http://my.37.com/login.html?url=http%3A%2F%2Fgame.37.com%2Fplay.php%3Fgame_id%3D237%26sid%3D3613";
            //request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
            //request.Headers["Accept-Language"] = "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4";
            Print(request);

            ConsoleBLL.WriteLine("进入游戏..");
            request = net.SendRequest(enterGameUrl, "GET", cookies);
            Print(request);

            ConsoleBLL.WriteLine("连接游戏服务器8000..");
            request = net.SendRequest(registerServerUrl, "GET", cookies);
            var html = net.GetResponseHtmlGzip(request);
            Print(html);

            TcpClient client = new TcpClient("s3613.37wandts.6ght.com", 8000);
            byte[] head = new byte[] { 0x00, 0x00, 0x00, 0x5B, 0x00, 0x01, 0x87, 0x70, 0x00, 0x04 };
            byte[] serverNo = Tools.GetAscII("3613");
            byte[] account = Tools.GetAscII("intorise");
            byte[] time = Tools.GetAscII(GetTime(html));
            byte[] singn = Tools.GetAscII(GetSign(html));
            var data = Tools.Contact(head, serverNo, new byte[] { 0x00, 0x08 }, account, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A }
                , time, new byte[] { 0x00, 0x01, 0x34, 0x00, 0x20 }, singn
                , new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30 });
            net.SendData(client, data, data.Length);
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x00, 0x01, 0x87, 0x6A, 0x0E, 0x1D, 0x54, 0x6B, 0x5A, 0x7D, 0xC9, 0x39, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x87, 0x6E, 0x00, 0x00, 0x00, 0x00 });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x87, 0x6E, 0x00, 0x00, 0x00, 0x00 });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x0D, 0x00, 0x01, 0x87, 0x6C, 0x00, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x03, 0xEA });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xD9, 0x72, 0x00 });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x07, 0xB1, 0xED, 0x00, 0x00, 0x00, 0x06 });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x08, 0x00, 0x09, 0x28, 0x99, 0x00, 0x00, 0x00, 0x01 });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x1A, 0x00, 0x02, 0x17, 0x8E, 0x00, 0x08, 0x69, 0x6E, 0x74, 0x6F, 0x72, 0x69, 0x73, 0x65, 0x0E, 0x1D, 0x54, 0x6B, 0x5A, 0x7D, 0xC9, 0x39, 0x00, 0x02, 0x2D, 0x31 });

            ///net.SendData(client, new byte[] { 0x0, 0x00, 0x00, 0x10, 0x00, 0x01, 0x8B, 0x51, 0x06, 0x4C, 0x10, 0xBF, 0x00, 0x06, 0x26, 0x26, 0x26, 0x26, 0x22, 0x03 });
            //net.SendData(client, new byte[] { });
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x00, 0x01, 0x8B, 0x5A, 0x00, 0x01, 0x86, 0xae, 0x00, 0x00, 0x00, 0x00 });//send 
            net.SendData(client, new byte[] { 0x00, 0x00, 0x00, 0x1C, 0x00, 0x01, 0x8B, 0x51, 0x10, 0xBF, 0x14, 0x75, 0x00, 0x12, 0x23, 0x03, 0x02, 0x23, 0x01, 0x02, 0x22, 0x01, 0x21, 0x22, 0x01, 0x23, 0x25, 0x41, 0x46, 0x46, 0x46, 0x44 });

            ObjectState state = new ObjectState { Client = client };
            client.GetStream().BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(ReadData), state);
        }

        void ReadData(IAsyncResult result)
        {
            ObjectState obj = (ObjectState)result.AsyncState;
            var stream = obj.Client.GetStream();
            var length = stream.EndRead(result);
            if (length > 0)
            {
                PrintData("收到服务器返回的数据：", obj.Buffer, length);
            }
            ObjectState state = new ObjectState { Client = obj.Client };
            obj.Client.GetStream().BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(ReadData), state);
        }

        void Print(HttpWebRequest request)
        {
            var response = (HttpWebResponse)request.GetResponse();
            var html = net.GetResponseHtmlGzip(response);
            ConsoleBLL.WriteLine(html);
            ConsoleBLL.WriteLine("--------------------------------------------");
            var cookieCollection = cookies.GetCookies(new Uri(loginUrl));
            for (int i = 0; i < cookieCollection.Count; i++)
            {
                ConsoleBLL.WriteLine(cookieCollection[i].Name + ":" + cookieCollection[i].Value);
            }
            ConsoleBLL.WriteLine("location:" + response.Headers["location"]);
            registerServerUrl = response.Headers["location"];
        }

        void Print(string html)
        {
            ConsoleBLL.WriteLine(html);
            ConsoleBLL.WriteLine("-----------------Cookies---------------------------");
            var cookieCollection = cookies.GetCookies(new Uri(loginUrl));
            for (int i = 0; i < cookieCollection.Count; i++)
            {
                ConsoleBLL.WriteLine(cookieCollection[i].Name + ":" + cookieCollection[i].Value);
            }
        }

        string GetSign(string html)
        {
            var tag = "sign:		\"";
            int index = html.IndexOf(tag);
            if (index > -1)
            {
                return html.Substring(index + tag.Length, 32);
            }
            return "";
        }

        string GetTime(string html)
        {
            var tag = "time:       \"";
            int index = html.IndexOf(tag);
            if (index > -1)
            {
                return html.Substring(index + tag.Length, 10);
            }
            return "";
        }

        string GetSign0()
        {
            var cookieCollection = cookies.GetCookies(new Uri(loginUrl));
            var passport = cookieCollection["passport_37wan_com"];
            return passport.Value.Substring(passport.Value.Length - 32, 32);
        }

        //打印数据
        private void PrintData(string text, byte[] datas, int length)
        {
            string s = "";
            for (int i = 0; i < length; i++)
            {
                s += datas[i].ToString("X2") + " ";
            }

            text = DateTime.Now.ToString("HH:mm:ss:ffff") + " " + text + "\r\n" + s + "\r\n" + "UTF-8解码：" + Tools.ConvertChar(UTF8Encoding.UTF8.GetString(datas, 0, length) + "\r\n\r\n----------------------------------------------------------------------------------------------");
        }
    }

    class ObjectState
    {
        public byte[] Buffer = new byte[10240];
        public TcpClient Client { get; set; }
    }
}
